import glob, os, shutil
import subprocess
if __name__ == '__main__':
    training_folder_names = glob.glob('training_*')
    print training_folder_names
    box_names = []
    tr_names = []
    for training_folder_name in training_folder_names:
        if os.path.isfile(training_folder_name): continue
        tif_path = os.path.join(training_folder_name, 'training.tif');
        box_path = os.path.join(training_folder_name, 'training.box');
        box_names.append(box_path)
        tr_names.append(training_folder_name + '.tr')
        print subprocess.call(['tesseract', tif_path, training_folder_name, 'nobatch', 'box.train'])
    unicharset_extractor_args = ['unicharset_extractor']
    unicharset_extractor_args.extend(box_names)
    print subprocess.call(unicharset_extractor_args)
    
    mftraining_args = ['mftraining', '-U', 'unicharset', '-O', 'peng.unicharset']
    mftraining_args.extend(tr_names)
    print subprocess.call(mftraining_args)
    
    cntraining_args = ['cntraining']
    cntraining_args.extend(tr_names)
    print subprocess.call(cntraining_args)
    os.rename('normproto', 'peng.normproto')
    os.rename('Microfeat', 'peng.Microfeat')
    os.rename('inttemp', 'peng.inttemp')
    os.rename('pffmtable', 'peng.pffmtable')
    print subprocess.call(['combine_tessdata', 'peng.'])
    for tr_name in tr_names:
        os.remove(tr_name)
    shutil.copy('peng.traineddata', 'tessdata');
    for tessdata_file in glob.glob('peng.*'):
        os.remove(tessdata_file)
    for log_file in glob.glob('*.log'):
        os.remove(log_file)
    for log_file in glob.glob('*.txt'):
        os.remove(log_file)
    os.remove('unicharset')
    
    
    
    